import {defineStore} from "pinia";
import {ref} from "vue";
import {createOrganization, getOrganizationList} from "@/services/api/organization";
import {message} from "ant-design-vue";
import {getUserId} from "@/utils/auth.ts";

export const useOrgStore = defineStore('organization', ()=>{
    const list = ref<OrganizationItem[]>([])
    const data = ref<OrganizationItem>()
    const id = ref<string>('')
    const loading = ref<boolean>(false)
    const getList = async (force?:boolean)=>{
        // 如果已经获取过数据，则不再获取
        if(!force && list.value.length > 0){
             return
        }
        loading.value = true
        try {
            const user_id= getUserId()
            if(!user_id){
                return message.error('获取用户ID失败,请您重新登录')
            }
            const res:ApiResponse<OrganizationItem[]> = await getOrganizationList(user_id)
            if (res.code === 200){
                list.value = res.data
            }
        }catch{return}
        finally {
            setTimeout(()=>loading.value = false,100)
        }
    }
    const setCurrentData = (_data:OrganizationItem)=>{
        data.value = _data
        id.value = _data.id
    }
    const create = async (params:OrganizationFormType)=>{
        const res =  await createOrganization(params)
        if(res.code === 200){
            await getList(true)
        }
        return res
    }
    const update = async ()=>{}
    const remove = async ()=>{}

    return {id,list,data,getList,create,update,remove,setCurrentData,loading}
},{
    persist: {
        omit: ['loading']
    }
})